package com.firegod.teacher.service;

import com.alibaba.fastjson.JSONObject;
import com.firegod.commonutils.result.ResultCode;
import com.firegod.servicebase.dao.TeacherRepository;
import com.firegod.servicebase.dao.UserRepository;
import com.firegod.servicebase.entity.Course;
import com.firegod.servicebase.entity.Teacher;
import com.firegod.servicebase.entity.User;
import com.firegod.servicebase.exceptionhandler.exception.GuliException;
import com.firegod.servicebase.service.BaseService;
import com.firegod.shiro.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Service
public class TeacherService extends BaseService<Teacher, Long, TeacherRepository> {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private UserRepository userRepository;

    public String login(String teacherId, String password) {
        //判断手机号是否正确
        Teacher teacher = baseRepository.getByUserId(teacherId);
        //判断对象是否为空
        teacher = Optional.ofNullable(teacher).orElseThrow(() -> GuliException.from(ResultCode.LOGIN_ERROR));

        //判断密码
        //因为存储到数据库密码肯定加密的
        //把输入的密码进行加密，再和数据密码进行比较
        //加密方式 MD5
        if (!teacher.getPassword().equalsIgnoreCase(DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8)))) {
            throw GuliException.from(ResultCode.LOGIN_ERROR);
        }

        return tokenService.createToken("Teacher: " + teacher.getUserId());

        //登录成功
        //生成token字符串，使用jwt字符串
//        return JwtUtils.getJwtToken(member.getId(), member.getNickname());
    }

    public String register(String teacherId, String password) {
        //判断手机号是否正确
        User user = userRepository.getByUserId(teacherId);
        //判断对象是否为空
        if (user != null) {
            throw GuliException.from(ResultCode.REDUPLICATE_TEACHER_ID_ERROR);
        }
        //判断密码
        //因为存储到数据库密码肯定加密的
        //把输入的密码进行加密，再和数据密码进行比较
        //加密方式 MD5
        Teacher teacher = new Teacher(teacherId);
        teacher.setPassword(DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8)));
        baseRepository.saveAndFlush(teacher);
        return tokenService.createToken("Teacher: " + teacher.getUserId());

        //登录成功
        //生成token字符串，使用jwt字符串
//        return JwtUtils.getJwtToken(member.getId(), member.getNickname());
    }

    public void create(String teacherId) {
        //判断手机号是否正确
        Teacher teacher = baseRepository.getByUserId(teacherId);
        //判断对象是否为空
        if (teacher != null) {
            throw GuliException.from(ResultCode.REDUPLICATE_TEACHER_ID_ERROR);
        }
        //判断密码
        //因为存储到数据库密码肯定加密的
        //把输入的密码进行加密，再和数据密码进行比较
        //加密方式 MD5
        teacher = new Teacher(teacherId);
        teacher.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes(StandardCharsets.UTF_8)));
        baseRepository.saveAndFlush(teacher);
        //登录成功
        //生成token字符串，使用jwt字符串
//        return JwtUtils.getJwtToken(member.getId(), member.getNickname());
    }

    public Map<String, Object> getTeacherInfo() {
        HashMap<String, Object> hashMap = new HashMap<>();
        String teacherId = tokenService.getCurrentUser().substring(9);
        Teacher teacher = baseRepository.getByUserId(teacherId);
        if (teacher == null) {
            throw GuliException.from(ResultCode.TEACHER_NOT_EXIST);
        }
        hashMap.put("userId", teacherId);
        hashMap.put("name", teacher.getName());
        hashMap.put("email", teacher.getEmail());
        hashMap.put("mobile", teacher.getMobile());
//        hashMap.put("courseList", teacher.getCourseList());
        return hashMap;
    }

    public void changePassword(String oldPassword, String password) {
        String teacherId = tokenService.getCurrentUser().substring(9);
        Teacher teacher = baseRepository.getByUserId(teacherId);
        if (teacher == null) {
            throw GuliException.from(ResultCode.TEACHER_NOT_EXIST);
        }
        if (!teacher.getPassword().equalsIgnoreCase(DigestUtils.md5DigestAsHex(oldPassword.getBytes(StandardCharsets.UTF_8)))) {
            throw GuliException.from(ResultCode.PASSWORD_ERROR);
        }
        teacher.setPassword(DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8)));
        baseRepository.saveAndFlush(teacher);
    }

    public void logout() {
        String teacherId = tokenService.getCurrentUser().substring(9);
        tokenService.deleteToken(teacherId);
    }

    public void changeInfo(String mobile, String email, String name) {
        String teacherId = tokenService.getCurrentUser().substring(9);
        Teacher teacher = baseRepository.getByUserId(teacherId);
        if (teacher == null) {
            throw GuliException.from(ResultCode.TEACHER_NOT_EXIST);
        }
        if (mobile != null) {
            teacher.setMobile(mobile);
        }
        if (email != null) {
            teacher.setEmail(email);
        }
        if (name != null) {
            teacher.setName(name);
        }
        baseRepository.saveAndFlush(teacher);
    }

    public JSONObject[] getAllCourses() {
        String userIdWithType = tokenService.getCurrentUser();
        if (!userIdWithType.substring(0, 7).equalsIgnoreCase("teacher")) {
            throw GuliException.from(ResultCode.TEACHER_NOT_EXIST);
        }
        return baseRepository.getByUserId(userIdWithType.substring(9)).getCourseList().stream().map(Course::show).toArray(JSONObject[]::new);
    }

    public HashMap<String, Object> getAllTeacher(int offset, int limit) {
        HashMap<String, Object> hashMap = new HashMap<>();
        var result = baseRepository.findAll(PageRequest.of(offset, limit));
        long lastSize = result.getTotalElements();
        hashMap.put("teacherList", result.getContent().stream().map(Teacher::show));
        hashMap.put("total", lastSize);
        return hashMap;
    }

    public HashMap<String, Object> getRecommendTeacher(int limit) {
        HashMap<String, Object> hashMap = new HashMap<>();
        var result = baseRepository.findAll();
        long lastSize = Math.min(result.size(), limit);
        hashMap.put("teacherList", result.stream().filter(Teacher::hasCourse).sorted(
                Comparator.comparing(Teacher::NumberOfCourse).reversed()
        ).limit(lastSize).map(Teacher::show));
        hashMap.put("total", lastSize);
        return hashMap;
    }

    public JSONObject[] getCourse() {
        String teacherId = tokenService.getCurrentUser().substring(9);
        Teacher teacher = baseRepository.getByUserId(teacherId);
        return teacher.getCourseList().stream().map(Course::show).toArray(JSONObject[]::new);
    }
}
